﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ValidationFramework.Web.MVC
{
	/// <summary>
	/// Resposible for coordinating the translation between framework rules and client rules
	/// </summary>
	public class RuleConverter : IRuleConverter
	{
		private readonly ClFunctionCallProviderDictionary scriptProviders;

		/// <summary>
		/// Initializes a new instance of the MapPropertyToElementRuleConverter class.
		/// </summary>
		/// <param name="scriptProviders"></param>
		public RuleConverter()
		{
			scriptProviders = new ClFunctionCallProviderDictionary();
		}
		/// <summary>
		/// Initializes a new instance of the MapPropertyToElementRuleConverter class.
		/// </summary>
		/// <param name="scriptProviders"></param>
		public RuleConverter(ClFunctionCallProviderDictionary scriptProviderDictionary)
		{
			scriptProviders = scriptProviderDictionary;
		}

		public ClientRule ConvertToClientRule(RuleInfo ruleInfo)
		{
			var serverRule = ruleInfo.Rule;
			var validator = serverRule.Specification;
			var provider = this.scriptProviders.GetProvider(validator);

			if (provider == null)
				return null;

			var er = new ClientRule();
			er.ErrorMessage = serverRule.ResolveErrorMessage(ruleInfo.MemberName, "Property");
			er.ClientFunctionCall = provider.GetClientFunctionCall(validator);

			return er;
		}
	}
}
